using OpenBlock.Block;
using OpenBlock.Math;
using OpenBlock.Properties;
using OpenBlock.Terrain;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace OpenBlock.Utils
{
    public class SingleCube : MonoBehaviour
    {
        private Mesh cubeMesh;
        private MeshFilter meshFilter;
        private MeshRenderer meshRenderer;

        public Color color;
        public Material opaque, rgb, transparent;
        public BlockFacing facing;

        private bool started;

        private void Awake()
        {
            cubeMesh = new Mesh();
            meshFilter = GetComponent<MeshFilter>();
            meshRenderer = GetComponent<MeshRenderer>();
        }

        private void OnEnable()
        {
            started = true;
            var test = new BlockState(BlockId.Grass);
            test.AddProperty("RGB", new Property(color.ToColorCode()));
            Rebuild(test);
        }

        private void OnDisable()
        {
            started = false;
        }

        private void OnValidate()
        {
            if (!started) return;
            var test = new BlockState(BlockId.Grass);
            test.AddProperty("RGB", new Property(color.ToColorCode()));
            Rebuild(test);
        }

        public void Rebuild(BlockState state)
        {
            cubeMesh.Clear();
            ChunkMeshBuilder cmb = new ChunkMeshBuilder();
            BlockRegistry.blocks[state.id].Model.BuildModel(state, ref cmb, Vector3.one * 0.5f, facing);
            cmb.Build(ref cubeMesh, out int oidx, out int cidx, out int tidx);
            int materialCount = 0;
            if (oidx != -1) materialCount++;
            if (cidx != -1) materialCount++;
            if (tidx != -1) materialCount++;

            Material[] materials = new Material[materialCount];
            if (oidx != -1) materials[oidx] = opaque;
            if (cidx != -1) materials[cidx] = rgb;
            if (tidx != -1) materials[tidx] = transparent;

            meshFilter.mesh = cubeMesh;
            meshRenderer.materials = materials;
        }
    }
}
